package com.mayikt;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @ClassName MtMayiktExecutor
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
public class MtMayiktExecutor {
    /**
     * 存放我们线程池 的容器
     */
    private BlockingQueue<Runnable> taskRunnables;
    /**
     * 一直正在运行的线程
     */
    private List<WorkThread> workThreads = new ArrayList<>();

    public MtMayiktExecutor(int maxThreads, int taskRunnableCount) {
        taskRunnables = new LinkedBlockingDeque<>(taskRunnableCount);
        workThreads = new ArrayList<>(maxThreads);
        for (int i = 0; i < maxThreads; i++) {
            WorkThread workThread = new WorkThread();
            workThread.start();
            workThreads.add(workThread);
        }

    }


    class WorkThread extends Thread {
        @Override
        public void run() {
            while (true) {
                Runnable runnable = taskRunnables.poll();
                if (runnable != null) {
                    runnable.run();
                }
            }
        }
    }

    /**
     * 提交线程任务
     *
     * @param runnable
     */
    public void executor(Runnable runnable) {
        taskRunnables.add(runnable);
    }

    public static void main(String[] args) {
        MtMayiktExecutor mtMayiktExecutor =
                new MtMayiktExecutor(3, 17);
        for (int i = 0; i < 30; i++) {
            int finalI = i;
            try {
                mtMayiktExecutor.executor(() -> System.out.println(Thread.currentThread().getName() + "," +
                        finalI));
            } catch (Exception e) {
                // 记录日志 采用日志记录方式
            }
        }
        //线程复用机制和拒绝策略 自动扩容 生产环境如果线程

    }
}
